<?php

namespace addons\facrm\library\cloudcall\engine;


use fast\Http;

/**
 * tycc100.com
 * @author amplam 122795200@qq.com
 */
class Tycc100 extends Server
{
    protected $httpwww="http://apis.tycc100.com";
    /**
     * 测试的账号
     * @var array|string[]
     */
    protected $config=[
        'acount_id'=>'',
        'secret'=>'',
    ];

    /**
     * 构造方法
     * @param $config
     */
    public function __construct($config = array())
    {
        $this->config =$config? $config:$this->config;
    }

    /**
     * 拨打
     * @param $config
     * @param $data Exten
     * @param array $extend 扩展参数
     * @return bool
     */
    public function call($data=array(),$extend=array()){
        if (!isset($data['exten'])||!$data['exten']){
            $this->error='联系方式不能为空';
            return  false;
        }
        if (!isset($data['from_exten'])||!$data['from_exten']){
            $this->error='坐席不能为空';
            return  false;
        }
        $result=$this->dialout($data,$extend);
        $result=json_decode($result,true);
        if (isset($result['Succeed'])&&$result['Succeed']){
            return  $result;
        }
        $this->error=isset($result['Message'])?$result['Message']:$result['message'];

        return  false;
    }

    /**
     * 外呼接口
     * @return bool|string
     */
    public function dialout($data,$extend){
        $strtime=datetime(time(),'YmdHis');
        $sig=$this->getSig($strtime);
        $send_data=array(
            'FromExten'=>$data['from_exten'],//员工坐席
            'Exten'=>$data['exten'],//第一个电话号码[客户电话]
			'ExtenType'=>$data['exten_type'],//Local/sip/gateway外呼时强制坐席使用该接听方式进行外呼。Local为“手机”,”gateway为“语音网关”
        );
        $header = [
            'Content-Type: application/json; charset=utf-8',
            'Authorization: '.$this->getAuthorization($strtime),
            'Content-Length: ' . strlen(json_encode($send_data)),
        ];
        $url=$this->httpwww."/v20160818/call/dialout/{$this->config['acount_id']}?sig=".$sig;
        return self::curl_post_content($url, json_encode($send_data), $header);
    }


    /**
     * 获取报表 TODO 看文档报表不存在先不做，有时间问问
     */
    public function statistics($data=array()){


        $strtime=datetime(time(),'YmdHis');
        $sig=$this->getSig($strtime);

        $send_data=array(
            'account'=>$this->config['acount_id'],
            'TimeType'=>'day',
        );
        $header = [
            'Content-Type: application/json; charset=utf-8',
            'Authorization: '.$this->getAuthorization($strtime),
            'Content-Length: ' . strlen(json_encode($send_data)),
        ];
        $url=$this->httpwww."/v20180426/callReport/openAgent/{$this->config['acount_id']}?sig=".$sig;
        return self::curl_post_content($url, json_encode($send_data), $header);
    }

    /**
     * 获取通话记录
     */
    public function getCallRecord($data){
        if (!isset($data['beginTime'])){
            $data['beginTime'] =datetime( time()-(86400*1), 'Y-m-d H:i:s') ;//开始时间
        }
        if (!isset($data['endTime'])){
            $data['endTime'] =datetime( time(), 'Y-m-d H:i:s');//结束时间
        }
        $strtime=datetime(time(),'YmdHis');
        $sig=$this->getSig($strtime);


        $send_data=array(
            'beginTime'=> $data['beginTime'],
            'endTime'=>$data['endTime'],
            'getAll'=>true,
        );
        isset($data['callNo'])?$send_data['callNo']=$data['callNo']:'';//主叫号码
        isset($data['calledNo'])?$send_data['calledNo']=$data['calledNo']:'';//被叫号码

        $header = [
            'Content-Type: application/json; charset=utf-8',
            'Authorization: '.$this->getAuthorization($strtime),
            'Content-Length: ' . strlen(json_encode($send_data)),
        ];
        $url=$this->httpwww."/v20180426/cdr/getCCCdr/{$this->config['acount_id']}?sig=".$sig;
        return self::curl_post_content($url, json_encode($send_data), $header);
    }



    protected function getAuthorization($strtime){

       return base64_encode(  $this->config['acount_id'].":".$strtime);
    }
    protected function getSig($strtime){
        //sig的值为 32位大写MD5加密 （帐号Id + 帐号APISecret +时间戳）
        return strtoupper( md5($this->config['acount_id'].$this->config['secret'].$strtime));

    }
    public static function curl_post_content($url, $data = null, $header = [])
    {
        $ch = curl_init();
        if (substr_count($url, 'https://') > 0) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            $res = false;
        }
        curl_close($ch);

        return $res;
    }

}